<!-- 生成选项弹窗 -->
<template>
  <t-dialog
    v-loading="loading.visible"
    :element-loading-text="loading.text"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
    title="生成选项"
    width="500px"
    :height="isCustomSpreadCodeWay ? '700px' : '350px'"
    :visible="visible"
    :bodyScrollY="true"
    :closeDestroy="true"
    @onClickFooterButton="onClickFooterButton"
    @open="onOpen"
    @closed="onClosed"
  >
    <el-form
      ref="form"
      label-position="top"
      :model="form"
      :rules="$options.constants.rules"
    >
      <el-form-item label="铺码方式：" prop="spreadCodeWay">
        <el-select
          class="w-full"
          v-model="form.spreadCodeWay"
          placeholder="请选择铺码方式"
          @change="() => (this.form.codepointsize = 0)"
        >
          <el-option
            v-for="i in $options.constants.spreadCodeWayOption"
            :key="i.value"
            :label="i.label"
            :value="i.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="码点间距：" prop="codepointsize">
        <el-radio-group v-model="form.codepointsize">
          <el-radio
            v-for="i in $options.constants.codepointsizeList"
            :key="i.value"
            :label="i.value"
            :disabled="isDisabledRadio(i.value)"
            >{{ i.label }}</el-radio
          >
        </el-radio-group>
      </el-form-item>
      <!-- 自定义 -->
      <div v-if="isCustomSpreadCodeWay">
        <el-form-item label="PDF文档铺码类型：" prop="PDFDocumentType">
          <el-select
            class="w-full"
            v-model="form.PDFDocumentType"
            placeholder="请选择铺码方式"
          >
            <el-option
              v-for="i in $options.constants.PDFDocumentTypeOption"
              :key="i.value"
              :label="i.label"
              :value="i.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="铺码码点大小：" prop="spreadCodeSize">
          <el-select
            class="w-full"
            v-model="form.spreadCodeSize"
            placeholder="请选择铺码方式"
          >
            <el-option
              v-for="i in $options.constants.spreadCodeSizeOption"
              :key="i.value"
              :label="i.label"
              :value="i.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="铺码文件打印机DPI：" prop="spreadCodeFilePrintDPI">
          <el-select
            class="w-full"
            v-model="form.spreadCodeFilePrintDPI"
            placeholder="请选择铺码方式"
            @change="() => (this.form.codepointsize = 0)"
          >
            <el-option
              v-for="i in $options.constants.spreadCodeFilePrintDPIOption"
              :key="i.value"
              :label="i.label"
              :value="i.value"
            ></el-option
          ></el-select>
        </el-form-item>
        <el-form-item label="铺码模式：" prop="spreadCodeMode">
          <el-select
            class="w-full"
            v-model="form.spreadCodeMode"
            placeholder="请选择铺码方式"
          >
            <el-option
              v-for="i in $options.constants.spreadCodeModeOption"
              :key="i.value"
              :label="i.label"
              :value="i.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </div>
      <el-form-item label="页面范围：" prop="pageRange">
        <div class="flex items-center">
          <el-select
            class="flex-1 mr-4"
            v-model="form.pageRange"
            multiple
            collapse-tags
            placeholder="请选择页面范围"
          >
            <el-option
              v-for="i in pageRangeOption"
              :key="i.value"
              :label="i.label"
              :value="i.value"
            ></el-option>
          </el-select>
          <el-checkbox v-model="isSelectAllPages">全选</el-checkbox>
        </div>
      </el-form-item>
    </el-form>
  </t-dialog>
</template>

<script>
import * as local from "@/apis/local-spread-code";
import { getSpreadCodeSchedule } from "@/apis/spread-code-schedule";
import { getStoreValue, getStoreAllKey } from "@/common/indexedDB";
import { pxToActualSize, loading1 } from "@/common/utils";
import {
  codepointmode,
  codepointtype,
  imagesize,
  imagedpi,
  pdftype,
  codepointsize,
} from "@/common/constants";
import TDialog from "@/components/TDialog.vue";
export default {
  components: {
    TDialog,
  },
  constants: {
    spreadCodeWayOption: codepointmode,
    PDFDocumentTypeOption: codepointtype,
    spreadCodeSizeOption: imagesize,
    spreadCodeFilePrintDPIOption: imagedpi,
    spreadCodeModeOption: pdftype,
    codepointsizeList: codepointsize,
    rules: {
      spreadCodeWay: [
        { required: true, message: "请选择铺码方式", trigger: "blur" },
      ],
      PDFDocumentType: [
        { required: true, message: "请选择PDF文档铺码类型", trigger: "blur" },
      ],
      spreadCodeSize: [
        { required: true, message: "请选择铺码码点大小", trigger: "blur" },
      ],
      codepointsize: [
        { required: true, message: "请选择铺码码点大小", trigger: "blur" },
      ],
      spreadCodeFilePrintDPI: [
        {
          required: true,
          message: "请选择铺码文件打印机DPI",
          trigger: "blur",
        },
      ],
      spreadCodeMode: [
        { required: true, message: "请选择铺码模式", trigger: "blur" },
      ],
      pageRange: [
        { required: true, message: "请选择页码范围", trigger: "blur" },
      ],
    },
  },
  data() {
    return {
      visible: false,
      loading: {
        visible: false,
        text: "xxx",
      },
      pageRangeOption: [], // $页码范围选项
      form: {
        spreadCodeWay: 1, // $铺码方式
        PDFDocumentType: 3, // $PDF文档铺码类型
        spreadCodeSize: 2, // $铺码码点大小
        codepointsize: 0, // $铺码码点间距
        spreadCodeFilePrintDPI: 1, // $铺码文件打印DPI
        spreadCodeMode: 0, // $铺码模式
        pageRange: [], // $页码范围
        pageinfo: [], // $页码信息
      },
    };
  },
  computed: {
    // 是否为自定义铺码方式
    isCustomSpreadCodeWay({ form }) {
      return form.spreadCodeWay === 0;
    },
    isSelectAllPages: {
      get({ form: { pageRange }, pageRangeOption }) {
        return pageRangeOption.every((i) => pageRange.includes(i.value));
      },
      set(val) {
        this.form.pageRange = val
          ? this.pageRangeOption.map((i) => i.value)
          : [];
      },
    },
    isDisabledRadio({ form: { spreadCodeWay, spreadCodeFilePrintDPI } }) {
      return (value) => {
        if (value !== 1) {
          return false;
        }
        if (spreadCodeWay === 0) {
          return spreadCodeFilePrintDPI === 0;
        } else {
          return [1, 2].includes(spreadCodeWay);
        }
      };
    },
  },
  methods: {
    open() {
      this.visible = true;
    },
    // 开启弹窗触发
    async onOpen() {
      await new Promise((resolve) => this.$nextTick(resolve));
      await loading1(async () => await this.getPageData(), "获取页码数据中...");
    },
    // 弹窗关闭触发
    onClosed() {
      this.$refs.form.resetFields();
    },
    // 生成选项弹窗底部按钮
    onClickFooterButton(name) {
      switch (name) {
        case "取消": {
          this.visible = false;
          break;
        }
        case "确定": {
          this.submit();
          break;
        }
      }
    },
    // 提交
    async submit() {
      const valid = await new Promise((resolve) =>
        this.$refs.form.validate(resolve)
      );
      if (!valid) return;
      this.paramsParse(this.form);
    },
    // 获取所有页数据
    async getPageData() {
      const response = await getStoreAllKey(this.$route.params.name);
      if (response.code !== 200) {
        // $异常
        return;
      }
      const pageList = response.data.filter((i) => !isNaN(i));
      // 更新页码范围选项
      this.pageRangeOption = pageList.map((i) => ({
        label: `第${i}页`,
        value: i - 1,
      }));
      console.log("获取页码列表", response, pageList);
      const responses = await Promise.all(
        pageList.map((i) => getStoreValue(this.$route.params.name, i))
      );
      console.log("获取所有页数据", responses);
      this.form.pageinfo = responses.map((i, index) => {
        const pagenumber = pageList[index] - 1;
        return {
          pagenumber,
          pageid: pagenumber,
          areasinfo: i.data.map((j) => ({
            codepoint: {
              x: pxToActualSize(j.x),
              y: pxToActualSize(j.y),
            },
            actualpoint: {
              x: pxToActualSize(j.x),
              y: pxToActualSize(j.y),
            },
            actualsize: {
              width: pxToActualSize(j.width),
              height: pxToActualSize(j.height),
            },
            index: j._index ? j._index : 0,
            level: j._level,
            codetype: j._shape,
          })),
        };
      });
    },
    // 数据解析
    async paramsParse() {
      const keys = ["pdf", "writecode", "readcode"];
      const response = await Promise.all(
        keys.map((i) => getStoreValue(this.$route.params.name, i))
      );
      const obj = Object.fromEntries(
        keys.map((i, index) => [i, response[index].data])
      );
      console.log("获取信息", response, obj);
      const params = {
        urlpath: obj.pdf.url,
        writecode: obj.writecode ? obj.writecode.value : null,
        readcode: obj.readcode ? obj.readcode.value : null,
        codepointmode: this.form.spreadCodeWay,
        pagesinfo: this.form.pageinfo.filter((i) =>
          this.form.pageRange.includes(i.pagenumber)
        ),
        codepointsize: this.form.codepointsize,
        codepointinfo:
          this.form.spreadCodeWay === 0
            ? {
                codepointtype: this.form.PDFDocumentType,
                imagesize: this.form.spreadCodeSize,
                imagedpi: this.form.spreadCodeFilePrintDPI,
                pdftype: this.form.spreadCodeMode,
              }
            : null,
      };
      console.log(params);
      this.localSpreadCode(params);
    },
    // 局部铺码
    async localSpreadCode({
      urlpath,
      writecode,
      readcode,
      codepointmode,
      pagesinfo,
      codepointtype,
      imagesize,
      imagedpi,
      pdftype,
    }) {
      const res = await local.localSpreadCode({
        urlpath,
        writecode,
        readcode,
        codepointmode,
        pagesinfo,
        codepointtype,
        imagesize,
        imagedpi,
        pdftype,
      });
      const {
        data: {
          result,
          state: { code },
        },
      } = res;
      console.log("局部铺码", res);
      console.log("局部铺码", code, result);
      switch (code) {
        case 10000:
          this.loading.visible = true;
          this.loading.text = "解析PDF中...";
          this.getSpreadCodeSchedule(urlpath);
          break;
        default:
          break;
      }
    },
    // $获取铺码进度
    getSpreadCodeSchedule(filepath) {
      let timer = setInterval(async () => {
        const response = await getSpreadCodeSchedule(filepath);
        console.log("获取铺码进度", response);
        const {
          result: { speed, finish, message, filesname },
        } = response.data;
        // 更新百分比
        this.loading.text = `${parseFloat((speed * 100).toFixed(2))}%`;
        if (speed === 1) {
          clearInterval(timer);
          this.loading.visible = false;
          if (finish === 10000) {
            this.$confirm("铺码成功，是否下载已铺好的PDF", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "success",
            })
              .then(() => {
                filesname.map((i) => window.open(i, "_blank"));
                this.visible = false;
              })
              .catch(() => false);
          } else {
            this.$alert(message, "请求异常", {
              showClose: false,
              confirmButtonText: "确定",
            });
          }
        }
      }, 500);
    },
  },
};
</script>